import log from '../../../helpers/logger';
import { pushDiscordWebhook } from '../../../helpers/pushDiscordWebhook';
//import { validateLink } from '../../../helpers/dataValidation';

import {
  authorizedRouteHandler,
  ControllerMethodTypes,
  defaultRouteHandler,
} from '../../../../interfaces';
import { Request } from 'hyper-express';
import { showSelectedObjectKeys } from '../../../helpers/utilsJS';
import { minishop_order } from '../../../../../prisma/generated/uctoo';
import { setExCache } from '../../../helpers/redis';
import QRCode from 'qrcode';
import moment from 'moment';
import { getMinishopSpuFromDatabase } from '../../../services/uctoo/minishop_spu';
import { createMinishopOrderDetail, getMinishopOrderDetailFromDatabase, } from '../../../services/uctoo/minishop_order_detail';
import { getWechatopenUsersFromDatabase } from '../../../services/uctoo/wechatopen_users';
import { getUserAccount } from '../../../services/uctoo/user_has_account';
import { getUctooUserFromDatabase } from '../../../services/uctoo/uctoo_user';
import { calculateSkuTotalPrice } from '../../../services/uctoo/minishop_order';
import Websocket from 'ws';
import db from '../../../lib/db';
  //#region AutoCreateCode
import {
  createMinishopOrder,
  deleteMinishopOrderFromDatabase,
  deleteMultiMinishopOrderFromDatabase,
  editMinishopOrderInDatabase,
  editMultiMinishopOrderInDatabase,
  getMinishopOrderFromDatabase,
  getMinishopOrdersFromDatabase,
  queryMinishopOrdersFromDatabase,
  countMinishopOrders
} from '../../../services/uctoo/minishop_order';

class uctooMinishopOrderController {

  protected validateAndDestructureBody = async (
    req: Request,
    userId: string,
    actionType: ControllerMethodTypes
  ) => {
    const body = await req.json();
    const keysArray = Object.keys(body);       //如需自定义控制接收字段可在此定义，如['id','link','privacy_level','owner','description','group_id','stars'] ，默认接收所有提交字段
    const uctooMinishopOrder = showSelectedObjectKeys(body, keysArray) as minishop_order;
    uctooMinishopOrder.creator = userId;

    return uctooMinishopOrder;
  };
  public add: authorizedRouteHandler = async (req, res) => {
    try {
      const user = res.locals.id.user;
      const uctooMinishopOrder = await this.validateAndDestructureBody(
        req,
        user,
        ControllerMethodTypes.ADD
      );
      if (!uctooMinishopOrder) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

      const createdMinishopOrder = await createMinishopOrder(uctooMinishopOrder);
      if (!createdMinishopOrder) return res.status(500).json({ errno: "50001", errmsg: "database query failed" });

      res.status(200).json(createdMinishopOrder);
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public edit: authorizedRouteHandler = async (req, res) => {
    try {
      const user = res.locals.id.user;
      const body = await req.json();
      const { id,ids,force } = body;

      if(ids){
        const uctooMinishopOrder = await this.validateAndDestructureBody(
          req,
          user,
          ControllerMethodTypes.EDIT
        );
        if (!uctooMinishopOrder) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

        const editedMinishopOrder = await editMultiMinishopOrderInDatabase(uctooMinishopOrder, JSON.parse(ids), user);
        
        if (typeof editedMinishopOrder === 'object' && 'success' in editedMinishopOrder) {
          if (!editedMinishopOrder.success) {
            return res.status(403).json({
              errno: "40301", 
              errmsg: editedMinishopOrder.reason,
              ...(editedMinishopOrder.minishopOrderId && { minishopOrderId: editedMinishopOrder.minishopOrderId })
            });
          }
          return res.status(200).json(editedMinishopOrder.data);
        }
        
        res.status(200).json(editedMinishopOrder);
      }else{
        const uctooMinishopOrder = await this.validateAndDestructureBody(
          req,
          user,
          ControllerMethodTypes.EDIT
        );
        if (!uctooMinishopOrder) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

        const editedMinishopOrder = await editMinishopOrderInDatabase(uctooMinishopOrder, uctooMinishopOrder.id, user);
        
        if (typeof editedMinishopOrder === 'object' && 'success' in editedMinishopOrder) {
          if (!editedMinishopOrder.success) {
            return res.status(403).json({ errno: "40301", errmsg: editedMinishopOrder.reason });
          }
          return res.status(200).json(editedMinishopOrder.data);
        }
        res.status(200).json(editedMinishopOrder);
      }      
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public delete: authorizedRouteHandler = async (req, res) => {
    try {
      const body = await req.json();
      const { id,ids,force } = body;
      const user = res.locals.id.user;

      if(ids){
        const deletionResult = await deleteMultiMinishopOrderFromDatabase(JSON.parse(ids), force, user);
        
        if (typeof deletionResult === 'object' && 'success' in deletionResult) {
          if (!deletionResult.success) {
            return res.status(403).json({
              errno: "40301", 
              errmsg: deletionResult.reason,
              ...(deletionResult.minishopOrderId && { minishopOrderId: deletionResult.minishopOrderId })
            });
          }
          return res.status(200).json({ desc: '删除成功' });
        }
        
      }else{
        const deletionResult = await deleteMinishopOrderFromDatabase(id, force, user);
        
        if (typeof deletionResult === 'object' && 'success' in deletionResult) {
          if (!deletionResult.success) {
            return res.status(403).json({ errno: "40301", errmsg: deletionResult.reason });
          }
          return res.status(200).json({ desc: '删除成功' });
        }
        
      }

      res.status(200).json({ desc: '删除成功' });
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public getSingle: authorizedRouteHandler = async (req, res) => {
    try {
      const { id } = req.params;
      const user = res.locals.id.user;

      const minishopOrderFromDb = await getMinishopOrderFromDatabase(id, user);
      if (!minishopOrderFromDb) {
        return res.status(404).json({ 
          errno: "40401", 
          errmsg: '未找到该实体或您没有权限访问' 
        });
      }

      res.status(200).json(minishopOrderFromDb);
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public getMany: authorizedRouteHandler = async (req, res) => {
    try {
      const limit = parseInt(req.params.limit);
      const page = parseInt(req.params.page) || 0;
      const skip = parseInt(req.params.skip) || 0;
      const query = req.query;
      
      if (limit > 100) return res.status(400).json({ errno: "40002", errmsg: '请求数量不能超过100条' });
      if (isNaN(limit)) return res.status(400).json({ errno: "40003", errmsg: '请求数量必须是数字' });
      
      const user = res.locals.id.user;
      const totalCount = await countMinishopOrders(user);
      
      if (query) {
        const minishopOrdersFromDb = await queryMinishopOrdersFromDatabase(limit, page, skip, query, user);
        if (!minishopOrdersFromDb) return res.status(404).json({ errno: "40401", errmsg: '未找到符合条件的实体' });

        res.status(200).json({
          currentPage: page,
          totalCount: totalCount,
          totalPage: Math.ceil(Number(totalCount)/limit),
          minishopOrders: minishopOrdersFromDb
        });
      } else {
        const minishopOrdersFromDb = await getMinishopOrdersFromDatabase(limit, skip, page, user);
        if (!minishopOrdersFromDb) return res.status(404).json({ errno: "40401", errmsg: '未找到符合条件的实体' });

        res.status(200).json({
          currentPage: page,
          totalCount:totalCount,
          totalPage: Math.ceil(Number(totalCount)/limit),
          minishopOrders: minishopOrdersFromDb
        });
      }


    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  //#endregion AutoCreateCode

  protected validateAndCreateOrder = async (
    req: Request,
    userId: string,
    actionType: ControllerMethodTypes
  ) => {
    try {
      const body = await req.json();
      const { appid } = req.query;
      //查询用户
      const wechatopenUsersFromDb = await getWechatopenUsersFromDatabase(userId);
      if (!wechatopenUsersFromDb) return false;
      log.info(body);
      const snowId = require('simple-flakeid');
      let gen1 = new snowId.SnowflakeIdv1({ workerId: 1 });
      body['out_order_id'] = gen1.NextId().toString();                                 //雪花算法生成订单唯一id
      body['openid'] = wechatopenUsersFromDb.openid;
      body['type'] = 0;
      body['platform'] = 'H5';
      body['status'] = 10;
      body['appid'] = appid;
      body['creator'] = userId;
      const keysArray = Object.keys(body);       //如需自定义控制接收字段可在此定义，如['id','link','privacy_level','owner','description','group_id','stars'] ，默认接收所有提交字段
      const uctooMinishopOrder = showSelectedObjectKeys(body, keysArray) as minishop_order;
      //  log.info(userId);
      log.info(uctooMinishopOrder);
      //  uctooMinishopOrder.creator = userId;
      return uctooMinishopOrder;
    } catch (e) {
      log.error({ err: e.message, desc: e });
      return false;
    }

  };

  //生成被扫二维码
  public createVmcOrderQrcode: defaultRouteHandler = async (req, res) => {
    try {
      //需要有用户登录态
      const user = res.locals.id.user;
      if (!user) return res.status(400).json({ err: 'isUserLogined', desc: '提交数据格式错误' });
      //前端传来的订单数据
      const body = await req.json();
      log.info(body);
      const { appid } = req.query;
      log.info(appid);
      if (!appid) {
        return res.status(400).json({ err: 'isParamValidated', desc: '提交数据格式错误' });
      }
      const uctooMinishopOrder = await this.validateAndCreateOrder(
        req,
        user,
        ControllerMethodTypes.ADD
      );
      console.log(uctooMinishopOrder);
      if (!uctooMinishopOrder) return res.status(400).json({ err: 'isUserValidated', desc: '提交数据格式错误' });

      const createdMinishopOrder = await createMinishopOrder(uctooMinishopOrder);
      if (!createdMinishopOrder) return res.status(500).end();

      try {
        const domain = process.env.API_URL;
        const device_id = 'test00002';
        const params = '?' + 'order_id=' + createdMinishopOrder.id + '&device_id=' + device_id + '&user_id=' + 'testuser123';
        const url = domain + '/api/uctoo/minishop_order/edit' + params;
        const qrCodeImage = await QRCode.toDataURL(url);
        res.status(200).json({
          qrCode: qrCodeImage,
          orderId: createdMinishopOrder.id
        });
        /*    res.status(200).send(`<!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <title>显示qrCodeImage</title>
  </head>
  <body><img src="${qrCodeImage}" alt="QR Code" /></body>
  </html>`); */
      } catch (e) {
        log.error({ err: e.message, desc: e });
        return res.status(500).json({ err: e.message, desc: e });
      }

    } catch (e) {
      log.error({ err: e.message, desc: e });
      return res.status(500).json({ err: e.message, desc: e });
    }
  };

  /**生成H5用户订单
   * @see https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/ministore/minishopopencomponent/API/order/get_order_detail.html
   * */
  public createUserOrder: authorizedRouteHandler = async (req, res) => {
    try {
      //需要有用户登录态
      log.info('createWechatopenUserOrder');
      const user = res.locals.id.user;
      log.info(user);
      if (!user) return res.status(400).json({ err: 'isUserLogined', desc: '提交数据格式错误' });
      
      const body = await req.json();
      log.info(body);
      const appid = body.appid;
      if (!appid) {
        return res.status(400).json({ err: 'isParamValidated', desc: '提交数据格式错误' });
      }
      const user_type = body.user_type;
      let userInfo = null;
      // 通过用户类型取出用户信息
      if(user_type === 'uctoo_user'){
        const UctooUserFromDb = await getUctooUserFromDatabase(user);
        if (!UctooUserFromDb) return  res.status(400).json({ err: 'isUserLogined', desc: '缺少用户信息' });
        log.info('wechatopenUsersFromDb');
        log.info(UctooUserFromDb);
        //取出uctoo_user关联的user_has_account帐号获取openid
        const userAccount = await getUserAccount(UctooUserFromDb.id);
        log.info('userAccount');
        //用关联帐号的openid补充userInfo
        if (userAccount) {
          UctooUserFromDb['openid'] = userAccount.openid
        }
        log.info(UctooUserFromDb);
        userInfo = UctooUserFromDb;
      }
      if(user_type === 'wechatopen_users'){
        const wechatopenUsersFromDb = await getWechatopenUsersFromDatabase(user);
        if (!wechatopenUsersFromDb) return  res.status(400).json({ err: 'isUserLogined', desc: '缺少用户信息' });
        log.info('wechatopenUsersFromDb');
        log.info(wechatopenUsersFromDb);
        userInfo = wechatopenUsersFromDb;
      }
      log.info('userInfo');
        log.info(userInfo);

      let randomNumber = Math.floor(1000 + Math.random() * 9000);
      const outTradeNo = `${moment().format("YYYYMMDDHHmmss")}${randomNumber}`
      const uctooMinishopOrder = await this.validateAndDestructureBody(
        req,
        user,
        ControllerMethodTypes.ADD
      );
      log.info('user');
      log.info(user);
      console.log(uctooMinishopOrder);
      if (!uctooMinishopOrder) return res.status(400).json({ err: 'isUserValidated', desc: '提交数据格式错误' });

      //  先取出 minishop_spu
      const spuInfo = await getMinishopSpuFromDatabase(body.spu_id)
      if (!spuInfo) return res.status(400).json({ err: 'isSpuValidated', desc: '提交数据格式错误' });


      //  再生成 minishop_order_detail
      const product_infos = [{
        product_id: body.spu_id,
        sku_id: body.sku_id,
        sku_cnt: body.sku_cnt,
        on_aftersale_sku_cnt: 0,
        finish_aftersale_sku_cnt: 0,
        title: spuInfo.title,
        thumb_img: spuInfo.headimg.length ? spuInfo.headimg : "",
        sale_price: spuInfo.min_price,
        market_price: spuInfo.min_price,
        sku_attrs: []
      }];
      const pay_info = {
        prepay_id: "",
        transaction_id: "",
        prepay_time: 0,
        pay_time: 0,
        payment_method: 1
      };
      const price_info = {
        product_price: spuInfo.min_price,
        order_price: spuInfo.min_price,
        freight: 0,
        discounted_price: 0,
        is_discounted: false
      }
      const orderDetail = {
        product_infos: JSON.stringify(product_infos),
        pay_info: JSON.stringify(pay_info),
        price_info: JSON.stringify(price_info),
        status: 0,
        creator: user,
      }
      const createOrderDetail = await createMinishopOrderDetail(orderDetail)
      if (!createOrderDetail) return res.status(500).end();
      console.log(uctooMinishopOrder);
      const snowId = require('simple-flakeid');
      let gen1 = new snowId.SnowflakeIdv1({ workerId: 1 });
      let ext_json = {minishop_order_detail: createOrderDetail,user_type:user_type};
      let newOrder = {
        appid: appid,
        out_order_id: gen1.NextId().toString(),
        out_trade_no: '',
        order_detail_id: createOrderDetail.id,
        openid: userInfo.openid,
        status: 10,
        type: 0,
        platform: 'H5',
        creator: user,
        user_id: userInfo.id,
        ext_json: JSON.stringify(ext_json)
      };
      /*
      newOrder.out_order_id = gen1.NextId().toString();
      newOrder.out_trade_no = '';  //调起支付时生成，一个未支付订单可以多次调起支付，每次从transaction生成的预支付订单更新此值关联
      newOrder.order_detail_id = createOrderDetail.id;
      if (wechatUser) newOrder.openid = wechatUser.openid;
      newOrder.status = 10;
      newOrder.type = 0; //普通订单
      newOrder.platform = 'H5';*/
      console.log('newOrder');
      console.log(newOrder);
      log.info(newOrder);
      const createdMinishopOrder = await createMinishopOrder(newOrder);
      if (!createdMinishopOrder) return res.status(500).end();
      res.status(200).json(createdMinishopOrder);

    } catch (e) {
      log.error({ err: e.message, desc: e });
      return res.status(500).json({ err: e.message, desc: e });
    }
  };


  /**生成用户活动报名订单
   * @see https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/ministore/minishopopencomponent/API/order/get_order_detail.html
   * */
  public createUserEventOrder: defaultRouteHandler = async (req, res) => {
    try {
      //需要有用户登录态
      const user = res.locals.id.user;
      if (!user) return res.status(400).json({ err: 'isUserLogined', desc: '提交数据格式错误' });
      // 取出用户信息
      const wechatopenUsersFromDb = await getWechatopenUsersFromDatabase(user);
      if (!wechatopenUsersFromDb) return false;
      const body = await req.json();
      log.info(body);
      const appid = body.appid;
      if (!appid) {
        return res.status(400).json({ err: 'isParamValidated', desc: '提交数据格式错误' });
      }


      let randomNumber = Math.floor(1000 + Math.random() * 9000);
      const outTradeNo = `${moment().format("YYYYMMDDHHmmss")}${randomNumber}`
      const uctooMinishopOrder = await this.validateAndDestructureBody(
        req,
        user,
        ControllerMethodTypes.ADD
      );
      log.info('user');
      log.info(user);
      console.log(uctooMinishopOrder);
      if (!uctooMinishopOrder) return res.status(400).json({ err: 'isUserValidated', desc: '提交数据格式错误' });
      //更新报名用户信息
      const genderType = {"男":1,"女":2}
      const gender = genderType[body.gender];
      const wechatopenUserFromDb = await db.wechatopen_users.update({
        data: {
          nickname: body.nickname,
          gender:gender,
          phone_number: body.phone

        },
        where: {
          id: user,
        },
      });

      //  先取出 minishop_product_spu
      const spuInfo = await getMinishopSpuFromDatabase(body.spu_id)
      if (!spuInfo) return res.status(400).json({ err: 'isSpuValidated', desc: '提交数据格式错误' });
      //无需支付的活动订单创建订单，商品销量即增加
      const minishopSpuFromDb = await db.minishop_spu.update({
        data: {
          sales_count: {
            increment: 1,
          }
        },
        where: {
          id: spuInfo.id,
        },
      });


      //  再生成 minishop_order_detail
      const product_infos = [{
        product_id: body.spu_id,
        sku_id: body.sku_id,
        sku_cnt: body.sku_cnt,
        on_aftersale_sku_cnt: 0,
        finish_aftersale_sku_cnt: 0,
        title: spuInfo.title,
        thumb_img: spuInfo.headimg.length ? spuInfo.headimg : "",
        sale_price: spuInfo.min_price,
        market_price: spuInfo.min_price,
        sku_attrs: []
      }];
      const pay_info = {
        prepay_id: "",
        transaction_id: "",
        prepay_time: 0,
        pay_time: 0,
        payment_method: 1
      };
      const price_info = {
        product_price: spuInfo.min_price,
        order_price: spuInfo.min_price,
        freight: 0,
        discounted_price: 0,
        is_discounted: false
      }
      const orderDetail = {
        product_infos: JSON.stringify(product_infos),
        pay_info: JSON.stringify(pay_info),
        price_info: JSON.stringify(price_info),
        status: 0,
        creator: user,
      }
      const createOrderDetail = await createMinishopOrderDetail(orderDetail)
      if (!createOrderDetail) return res.status(500).end();
      console.log(uctooMinishopOrder);
      const snowId = require('simple-flakeid');
      let gen1 = new snowId.SnowflakeIdv1({ workerId: 1 });
      let newOrder = {
        appid: appid,
        out_order_id: gen1.NextId().toString(),
        out_trade_no: '',
        order_detail_id: createOrderDetail.id,
        openid: wechatopenUsersFromDb.openid,
        status: 10,
        type: 0,
        platform: 'H5',
        creator: user
      };
      /*
      newOrder.out_order_id = gen1.NextId().toString();
      newOrder.out_trade_no = '';  //调起支付时生成，一个未支付订单可以多次调起支付，每次从transaction生成的预支付订单更新此值关联
      newOrder.order_detail_id = createOrderDetail.id;
      if (wechatUser) newOrder.openid = wechatUser.openid;
      newOrder.status = 10;
      newOrder.type = 0; //普通订单
      newOrder.platform = 'H5';*/
      console.log('newOrder');
      console.log(newOrder);
      log.info(newOrder);
      const createdMinishopOrder = await createMinishopOrder(newOrder);
      if (!createdMinishopOrder) return res.status(500).end();

      //活动签到二维码
      const domain = process.env.API_URL;
        const params = '?' + 'order_id=' + createdMinishopOrder.id + '&openid=' + createdMinishopOrder.openid;
        const url = domain + '/api/uctoo/minishop_order/edit' + params;
        const qrCodeImage = await QRCode.toDataURL(url);

        //订单ticket存签到二维码
        const minishopOrderFromDb = await db.minishop_order.update({
          data: {
            ticket: qrCodeImage
          },
          where: {
            id: createdMinishopOrder.id,
          },
        });





        res.status(200).json({
          qrCode: qrCodeImage,
          MinishopOrder: createdMinishopOrder
        });

     // res.status(200).json(createdMinishopOrder);

    } catch (e) {
      log.error({ err: e.message, desc: e });
      return res.status(500).json({ err: e.message, desc: e });
    }
  };

    /**计算订单最终价格，用户选择配送方式、优惠券、积分等后，重新计算订单最终支付价格
   * @see https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/ministore/minishopopencomponent/API/order/get_order_detail.html
   * */
    public handleOrderFinalPrice: authorizedRouteHandler = async (req, res) => {
      try {
        //需要有用户登录态
        log.info('createWechatopenUserOrder');
        const user = res.locals.id.user;
        log.info(user);
        if (!user) return res.status(400).json({ err: 'isUserLogined', desc: '提交数据格式错误' });
        
        const body = await req.json();
        log.info(body);
        const appid = body.appid;
       /* if (!appid) {
          return res.status(400).json({ err: 'isParamValidated', desc: '缺少appid' });
        } */
        // 通过订单id取出订单信息
        const id = body.id;
        if (!id) {
          return res.status(400).json({ err: 'isParamValidated', desc: '缺少订单id' });
        }
        let minishopOrderData = await getMinishopOrderFromDatabase(id);
        if (!minishopOrderData) return res.status(400).json({ err: 'isParamValidated', desc: '缺少订单数据' });
        //查询订单详情数据
        let minishopOrderDetailData = await getMinishopOrderDetailFromDatabase(minishopOrderData.order_detail_id);
        if (!minishopOrderDetailData) return res.status(400).json({ err: 'isParamValidated', desc: '缺少订单详情数据' });
        //计算订单最终价格
        //订单中的多个商品合计价格
        let product_infos = JSON.parse(minishopOrderDetailData.product_infos);
        //循环product_infos汇总商品价格
        // 计算sku总价格
        let skuTotalPrice = calculateSkuTotalPrice(product_infos);
        console.log("Total Price:", skuTotalPrice);
        //todo:计算运费
        const freight = 0;

        //todo:计算优惠
        const discountedPrice = 0;

        //计算积分抵扣金额
        
        //更新订单数据
        const orderData = {final_price: skuTotalPrice};
        // 修复：添加用户ID作为第三个参数，并处理返回的包装对象
        const editResult = await editMinishopOrderInDatabase(orderData, id, user);
        if (editResult.success && editResult.data) {
          minishopOrderData = editResult.data;
          res.status(200).json(minishopOrderData);
        } else {
          res.status(400).json({ err: 'editFailed', desc: editResult.reason || '编辑订单失败' });
        }
  
      } catch (e) {
        log.error({ err: e.message, desc: e });
        return res.status(500).json({ err: e.message, desc: e });
      }
    };

  //统计订单数
  public countOrders: defaultRouteHandler = async (req, res) => {
    try {
      const totalCount = await countMinishopOrders();
      res.status(200).json({
        total: totalCount,
      });

    } catch (e) {
      log.error({ err: e.message, desc: e });
      return res.status(500).json({ err: e.message, desc: e });
    }
  };
  // 发送订单成功的消息给用户
  private sendMsgToUser(token, toUid, orderId) {
    const socket = new Websocket(`wss://localhost:${process.env.port}/ws/connect`);
    socket.on('open', function open() {
      console.log('connected');
      socket.send({ cmd: "auth", token })
    });

    socket.on('message', function incoming(data) {
      const msg = JSON.parse(data);
      if (msg.cmd == 'authAck') {
        socket.send({ cmd: "orderSuccess", token, toUid, orderId })
      } else if (msg.cmd == 'orderNotifyAck') {
        socket.close()
      }
    });

    socket.on('error', function (error) {
      console.error(error);
    });
  }
}

export default uctooMinishopOrderController;
